<template>
  <div ref="boxwrap" class="moudel-chart AlarmTypes">
    <div :id="id" :width="chartStyle.width" :height="chartStyle.height" class="chart" />
  </div>
</template>

<script>
import resize from '@/components/Charts/mixins/resize'
import { getAlertsStatus } from '@/api/screen'
import { cutLineName, sortArrObj } from '@/utils'
export default ({
  name: 'AlarmTypes',
  mixins: [resize],
  props: {
    width: {
      type: String,
      default: '150px'
    },
    height: {
      type: String,
      default: '150px'
    },
    isresize: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      id: 'AlarmTypes',
      chart: null,
      chartStyle: {
        width: '100%',
        height: '100%'
      },
      resData: null,
      color: ['rgba(255,16,16,1)', 'rgba(158,58,226,1)', 'rgba(222,67,27,1)', 'rgba(46,200,207,1)', 'rgba(108,80,243,1)', 'rgba(178,88,41,1)'],
      colorArr: [],
      fontColor: '#bebebe',
      currentView: {},
      alertType: { 0: '安全', 1: '参数', 2: '传感', 3: '电气', 4: '卡板', 5: '开停', 6: '门盖', 7: '系统', 8: '液位' },
      timer: null,
      refreshInterval: 1000 * 5 // 60
    }
  },
  // computed: {
  //   ...mapGetters([
  //     'regionid',
  //     'lineId'
  //   ])
  // },
  watch: {
    width: {
      immediate: true,
      handler: function(newval, oldval) {
        this.width = newval
      },
      deep: true
    },
    height: {
      immediate: true,
      handler: function(newval, oldval) {
        this.height = newval
      },
      deep: true
    },
    isresize(newval, oldval) {
      // console.log('AlarmTypes', newval)
      // this.movement = newval
      if (this.chart) {
        this.chart.resize()
      }
    }
  },
  mounted() {
    this.domResize()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null

    if (this.timer) {
      clearTimeout(this.timer)
      this.timer = null
    }
  },
  created() {
    this.getCurrentView()
    if (this.$route.path.indexOf('/screen') !== -1) {
      this.dataRefresh()
    }
  },
  methods: {
    getDomHeight() {
      this.chartStyle = {
        width: this.$refs.boxwrap.clientWidth + 'px',
        height: this.$refs.boxwrap.clientHeight + 'px'
      }
    },
    domResize() {
      const that = this
      // 引入 插件
      var elementResizeDetectorMaker = require('element-resize-detector')
      var erd = elementResizeDetectorMaker()
      const dom = this.$refs.boxwrap
      erd.listenTo(dom, function(element) {
        var width = element.clientWidth + 'px'
        var height = element.clientHeight + 'px'
        that.chartStyle = {
          width,
          height
        }
      })
      // console.log(JSON.stringify(that.chartStyle))
    },
    getCurrentView() {
      this.currentView = {
        regionid: this.$Cookies.get('currentReginid'),
        lineId: this.$Cookies.get('currentLineId')
      }
      this.getData()
    },
    getData() {
      getAlertsStatus(this.currentView).then(response => {
        this.resData = response.data
        this.colourList()
      }).then(() => {
        // 0929
        const topTenDataObj = {
          xAxis: [],
          datas: {}
        }
        const typeNum = {} // 每个类型的数量
        for (const k in this.alertType) {
          typeNum[this.alertType[k]] = 0
        }
        for (const k in this.resData) {
          const list = this.resData[k]
          let total = 0
          const arr = []
          list.forEach(item => {
            total += item.typeCount
            arr.push({ name: this.alertType[item.type], typeCount: item.typeCount })
            typeNum[this.alertType[item.type]] += item.typeCount
          })
          topTenDataObj.datas[k] = {
            lineName: cutLineName(k),
            total,
            list: arr
          }
        }
        const typeNumArr = [] // 按数量降序后的所有类型，可用于x轴
        for (const k in typeNum) {
          typeNumArr.push({ name: k, typeCount: typeNum[k] })
        }
        typeNumArr.sort(sortArrObj('typeCount', 'desc'))
        // console.log('按数量降序后的全部类型', typeNumArr)

        typeNumArr.forEach(item => {
          topTenDataObj.xAxis.push(item.name)
        })

        // 计算贡献度
        for (const k in topTenDataObj.datas) {
          topTenDataObj.datas[k].list.forEach(item => {
            item['rate'] = topTenDataObj.datas[k].total === 0 ? 0 : item.typeCount === 0 ? 0 : (item.typeCount / topTenDataObj.datas[k].total * 100).toFixed(1)
          })
        }

        // 生成bar图
        this.initChart(topTenDataObj)
      })
    },
    colourList() {
      this.color.forEach(element => {
        const arr = element.split(',')
        arr.pop()
        this.colorArr.push({
          color: element,
          dark: arr.join(',') + ',.8)',
          light: arr.join(',') + ',.5)'
        })
      })
    },
    initChart(seriesList) {
      // console.log(seriesList)
      const lineColor = ['orangered', 'deeppink']
      const barWidth = 15
      const barGap = 0 // barGap = 0 => num = 50 ; barGap = 50 => num = 25
      const num = 50

      const tempList = Object.values(seriesList.datas)
      const initVal = 0 - num * (tempList.length - 1)
      const series = []
      let arr1 = []
      let arr2 = []
      tempList.forEach((item, index) => {
        arr1 = []
        arr2 = []
        seriesList.xAxis.forEach(type => {
          item.list.forEach(elm => {
            if (type === elm.name) {
              arr1.push(elm.typeCount)
              arr2.push(elm.rate)
            } else {
              arr1.push(0)
              arr2.push(0)
            }
          })
        })
        const offset = initVal + num * 2 * index + '%'
        if (index === 0) {
          series.push(
            {
              z: index + 1,
              name: item.lineName,
              nameTextStyle: {
                color: this.fontColor
              },
              type: 'bar',
              barWidth: barWidth,
              barGap: 0 - barGap + '%',
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0, x2: 1, y: 0, y2: 0,
                  colorStops: [
                    { offset: 0, color: this.colorArr[index].dark },
                    { offset: 0.5, color: this.colorArr[index].dark },
                    { offset: 0.5, color: this.colorArr[index].light },
                    { offset: 1, color: this.colorArr[index].light }
                  ]
                }
              },
              label: {
                show: true,
                position: [barWidth / 2, -(barWidth)],
                color: this.fontColor,
                fontSize: 14,
                fontStyle: 'bold',
                align: 'center'
              },
              data: arr1
            },
            {
            // name: seriesList[i].lineName +'顶',
              z: index + 1,
              type: 'pictorialBar',
              symbolPosition: 'end',
              data: arr1,
              symbol: 'diamond',
              symbolOffset: [offset, '-50%'], // A ['-50%', '-50%']  B ['50%', '-50%']
              symbolSize: [barWidth, barWidth / 3 * 2],
              itemStyle: {
                borderColor: this.colorArr[index].color,
                color: this.colorArr[index].color
              },
              tooltip: {
                show: false
              }
            },
            {
              name: item.lineName + '贡献度',
              type: 'line',
              data: arr2,
              yAxisIndex: 1,
              symbol: 'circle',
              itemStyle: {
                color: lineColor[index]
              },
              label: {
                show: true,
                position: 'top',
                color: this.fontColor,
                fontSize: 14,
                fontStyle: 'bold',
                align: 'center',
                formatter: '{c}%'
              }
            }
          )
        } else {
          series.push(
            {
              z: index + 1,
              name: item.lineName,
              nameTextStyle: {
                color: this.fontColor
              },
              type: 'bar',
              barWidth: barWidth,
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0, x2: 1, y: 0, y2: 0,
                  colorStops: [
                    { offset: 0, color: this.colorArr[index].dark },
                    { offset: 0.5, color: this.colorArr[index].dark },
                    { offset: 0.5, color: this.colorArr[index].light },
                    { offset: 1, color: this.colorArr[index].light }
                  ]
                }
              },
              label: {
                show: true,
                position: [barWidth / 2, -(barWidth)],
                color: this.fontColor,
                fontSize: 14,
                fontStyle: 'bold',
                align: 'center'
              },
              data: arr1
            },
            {
            // name: seriesList[i].lineName +'顶',
              z: index + 1,
              type: 'pictorialBar',
              symbolPosition: 'end',
              data: arr1,
              symbol: 'diamond',
              symbolOffset: [offset, '-50%'], // A ['-50%', '-50%']  B ['50%', '-50%']
              symbolSize: [barWidth, barWidth / 3 * 2],
              itemStyle: {
                borderColor: this.colorArr[index].color,
                color: this.colorArr[index].color
              },
              tooltip: {
                show: false
              }
            },
            {
              name: item.lineName + '贡献',
              type: 'line',
              data: arr2,
              yAxisIndex: 1,
              symbol: 'circle',
              itemStyle: {
                color: lineColor[index]
              },
              label: {
                show: true,
                position: 'top',
                color: this.fontColor,
                fontSize: 14,
                fontStyle: 'bold',
                align: 'center',
                formatter: '{c}%'
              }
            }
          )
        }
      })

      this.chart = this.$echarts.init(document.getElementById(this.id), 'jyt-dark')
      this.chart.setOption({
        color: [this.color[0], this.color[1]],
        tooltip: {
          trigger: 'axis',
          confine: true,
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          top: '25%',
          left: '4%',
          right: '5%',
          bottom: '5%',
          containLabel: true
        },
        legend: {
          type: 'scroll',
          textStyle: {
            color: this.fontColor,
            align: 'right'
          },
          right: 10,
          top: 0,
          padding: 0,
          itemWidth: 20,
          itemHeight: 10
        },
        xAxis: [{
          name: '类型',
          nameTextStyle: {
            color: this.fontColor
          },
          nameGap: 5,
          margin: 40,
          type: 'category',
          data: seriesList.xAxis,
          axisLine: {
            lineStyle: {
              color: 'rgba(255,255,255,0.12)'
            }
          },
          axisLabel: {
            margin: 10,
            interval: 0,
            color: this.fontColor,
            fontSize: 14
          }
        }],
        yAxis: [
          {
            name: '次数',
            nameGap: 5,
            nameTextStyle: {
              color: this.fontColor
            },
            minInterval: 1,
            axisLabel: {
              color: this.fontColor
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: 'rgba(255,255,255,.3)'
              }
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(255,255,255,0.1)'
              }
            }
          },
          {
            name: '贡献度',
            show: false,
            type: 'value',
            max: 100
          }
        ],
        series: series

      })
    },
    dataRefresh() {
      if (this.timer) {
        clearTimeout(this.timer)
        this.timer = null
      }
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
      this.timer = setTimeout(() => {
        this.getData()
        this.dataRefresh()
      }, this.refreshInterval)
    }
  }
})
</script>

<style lang="scss">
  .moudel-chart{
    width: 100%;
    height: 100%;
    > div {
        width: 100%;
        height: 100%;
      }
  }
</style>
